package com.younio.local.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

/**
 * @desc:
 * @author: lan     [1728209643@qq.com]
 * @date: 2018-09-11 16:58
 */
public class JsonRedisSerializer<T> implements RedisSerializer<T> {

	private static final Charset charset = Charset.forName("UTF-8");

	private Class<T> clazz;

	public JsonRedisSerializer(Class<T> clazz) {
		super();
		this.clazz = clazz;
	}

	@Override
	public byte[] serialize(T t) throws SerializationException {
		if (t == null) {
			return new byte[0];
		}
		return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(charset);
	}

	@Override
	public T deserialize(byte[] bytes) throws SerializationException {
		if (bytes == null || bytes.length == 0) {
			return null;
		}
		return JSON.parseObject(new String(bytes, charset), clazz);
	}
}
